package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"path/filepath"
	"shop/models"
	"strings"
	"time"
)

type ShopController struct {
	beego.Controller
}

type JsonRes struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *ShopController) Add() {
	name := c.GetString("name")
	price, _ := c.GetFloat("price", 64)
	times := time.Now()
	cate := c.GetString("cate")
	source := c.GetString("source")
	shop := models.Shop{
		Name:   name,
		Price:  price,
		Times:  times,
		Cate:   cate,
		Source: source,
	}
	err := models.DB.Create(&shop).Error
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "添加成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
func (c *ShopController) Del() {
	Id, _ := c.GetInt("id")
	shop := models.Shop{Id: Id}
	err := models.DB.Delete(&shop).Error
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "删除失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "删除成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
func (c *ShopController) List() {
	page, _ := c.GetInt("p", 1)
	pageSize, _ := c.GetInt("s", 3)
	name := c.GetString("name")
	Jsondata := make(map[string]interface{})
	shop, total, err := models.MysqlList(page, pageSize, name)
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "分页失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		Jsondata["shop"] = shop
		Jsondata["total"] = total
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "分页成功",
			Data: Jsondata,
		}
		c.ServeJSON()
	}
}
func (c *ShopController) Upload() {
	file, header, err := c.GetFile("img")
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "文件接送失败",
			Data: nil,
		}
		c.ServeJSON()
	}
	defer file.Close()
	if header.Size > 5*1024*1024 {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "文件大小要大于5MB",
			Data: nil,
		}
		c.ServeJSON()
	}
	suffix := strings.ToLower(filepath.Ext(header.Filename))
	suffixMax := map[string]bool{
		".png": true,
		".jpg": true,
	}
	if !suffixMax[suffix] {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "文件格式不对",
			Data: nil,
		}
		c.ServeJSON()
	}
	path := "static/img/" + header.Filename
	err = c.SaveToFile("img", path)
	if err != nil {
		c.Data["json"] = JsonRes{
			Code: 500,
			Msg:  "文件上传失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		ImgSrc := "http://127.0.0.1:8080" + path
		c.Data["json"] = JsonRes{
			Code: 200,
			Msg:  "文件上传成功",
			Data: ImgSrc,
		}
		c.ServeJSON()
	}
}
